package com.zhyz.bookstore.dao.impl;

import com.zhyz.bookstore.dao.OrderDao;
import com.zhyz.bookstore.entity.OrderItems;
import com.zhyz.bookstore.entity.Orders;
import com.zhyz.bookstore.entity.User;
import com.zhyz.bookstore.util.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {




    /**
     * 添加订单信息
     * @param o
     */
    @Override
    public void save(Orders o) {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        List<Orders> ordersList = null;
        String sql = "insert into orders (ordernum,quantity,money,time,status,userId) values (?,?,?,?,?,?)";
        conn = JDBCUtils.getconnection();
        try {
            pstat = conn.prepareStatement(sql);
            pstat.setString(1, o.getOrdernum());
            pstat.setInt(2, o.getQuantity());
            pstat.setDouble(3, o.getMoney());
            pstat.setString(4, o.getTime());
            pstat.setInt(5, o.getStatus());
            pstat.setString(6, o.getUser().getId());
            pstat.executeUpdate();

            // 保存订单项信息
            List<OrderItems> items = o.getItems();
            for (OrderItems item : items) {
                String sql2 = "insert into orderitems (id,quantity,price,book_id,ordernum) values(?,?,?,?,?)";
                conn = JDBCUtils.getconnection();
                pstat = conn.prepareStatement(sql2);
                pstat.setString(1, item.getId());
                pstat.setInt(2, item.getQuantity());
                pstat.setDouble(3, item.getPrice());
                pstat.setString(4, item.getBookid());
                pstat.setString(5, item.getOrdernum());
                pstat.executeUpdate();
                StoreUpdate(item.getBookid(),item.getQuantity());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs, pstat, conn);
        }
    }

    @Override
    public User findUserByUserId(String userId) {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        User u = null;

        String sql = "SELECT * FROM user WHERE user_id = ?";
        conn = JDBCUtils.getconnection();

        try {
            pstat = conn.prepareStatement(sql);
            pstat.setString(1,userId);
            rs = pstat.executeQuery();

            if(rs.next()){

                u = new User(rs.getString(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                                rs.getString(5),rs.getString(6)
                               ,rs.getString(7) );

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtils.close(rs, pstat, conn);
        }


        return u;
    }



    /**
     * 销售出库操作
     * @param
     */
    private void StoreUpdate(String bookid, int quantity) {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        List<Orders> ordersList = null;
        String sql = "update bookdb set book_xiaonumber = book_xiaonumber+"+quantity+",book_kunumber=book_kunumber-"+quantity+" where book_id=?";
        try {
            conn = JDBCUtils.getconnection();
            pstat = conn.prepareStatement(sql);
            pstat.setString(1, bookid);
            pstat.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs, pstat, conn);
        }

    }

    /**
     * 根据用户id查询该用户的所有订单
     *
     * @param user
     * @return
     */
    @Override
    public List<Orders> queryOrdersByUser(User user) {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        List<Orders> ordersList = null;
        ordersList = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE userId = ?";

        OrderItemsDaoImpl oitemsimpl = new OrderItemsDaoImpl();
        conn = JDBCUtils.getconnection();
        try {
            pstat = conn.prepareStatement(sql);
            pstat.setString(1, user.getId());
            rs = pstat.executeQuery();

            while (rs.next()) {
                Orders o = new Orders(this.findUserByUserId(rs.getString(6))
                        , rs.getString(1)
                        , rs.getInt(2)
                        , rs.getDouble(3)
                        , rs.getString(4)
                        , rs.getInt(5),oitemsimpl.queryOrderItemsByOrderId(rs.getString(1)));
                ordersList.add(o);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(rs, pstat, conn);
        }
        return ordersList;
    }


    /**
     * 管理员查询订单信息
     *
     * @return
     */
    @Override
    public List<Orders> queryOrderByAdmin() {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        List<Orders> ordersList = null;
        ordersList = new ArrayList<>();
        OrderItemsDaoImpl oitemsimpl = new OrderItemsDaoImpl();
        String sql = "SELECT * FROM orders";
        conn = JDBCUtils.getconnection();
        try {
            pstat = conn.prepareStatement(sql);
            rs = pstat.executeQuery();
            while (rs.next()) {
                Orders o = new Orders(this.findUserByUserId(rs.getString(6))
                        , rs.getString(1)
                        , rs.getInt(2)
                        , rs.getDouble(3)
                        , rs.getString(4)
                        , rs.getInt(5)
                        ,oitemsimpl.queryOrderItemsByOrderId(rs.getString(1)));
                ordersList.add(o);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(rs, pstat, conn);
        }
        return ordersList;
    }

    /**
     * 根据订单id先删除订单项，再删除订单
     *
     * @param orderId
     * @return
     */
    @Override
    public boolean deleteOrderByOrderId(String orderId) {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        List<Orders> ordersList = null;
        boolean isDelete = false;
        int res;
        String sql1 = "DELETE FROM orderitems WHERE ordernum = ?";
        String sql2 = "DELETE FROM orders WHERE ordernum = ?";
        conn = JDBCUtils.getconnection();
        try {
            pstat = conn.prepareStatement(sql1);
            pstat.setString(1, orderId);
            res = pstat.executeUpdate();
            if (res > 0) {
                pstat = conn.prepareStatement(sql2);
                pstat.setString(1, orderId);
                res = pstat.executeUpdate();
                if (res > 0) {
                    isDelete = true;
                }
            } else {
                isDelete = false;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(rs, pstat, conn);
        }
        return isDelete;
    }


    /**
     * 管理员更改订单状态
     * @param orderId 订单号
     * @param status 订单状态
     * @return
     */
    @Override
    public boolean deliverOrder(String orderId, int status) {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        List<Orders> ordersList = null;
        boolean isDeliver = false;
        int res;
        String sql ="UPDATE orders SET status = ? WHERE ordernum = ?";
        conn = JDBCUtils.getconnection();
        try {
            pstat = conn.prepareStatement(sql);
            pstat.setInt(1, status);
            pstat.setString(2,orderId);
            res = pstat.executeUpdate();
            if (res > 0) {
                isDeliver = true;
            } else {
                isDeliver = false;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(rs, pstat, conn);
        }

        return isDeliver;
    }


}
